"""自制的flask服务器,用于局域网传输文件.

  2017-07-14 基本完成,代码未经优化,下载上传文件都在static/uploads文件夹
"""

import os

from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename

## 设定主机和端口
HOST = '0.0.0.0'
PORT = 5003

app = Flask(__name__)

## 主页
@app.route('/', methods = ["GET"])
@app.route('/index.html', methods = ["GET"])
def index():
  return render_template('index.html')
  
## 下载页面
@app.route('/download', methods = ["GET"])
def download():
  basepath = os.path.dirname(__file__)
  upload_path = os.path.join(basepath, r'static\uploads')
  filenames = os.listdir(upload_path)
  return render_template('download.html', filenames = filenames)

## 上传页面,如果是POST则是上传文件请求
@app.route('/upload', methods = ["GET", "POST"])
def upload():
  if request.method == 'POST':
    f = request.files['file']
    basepath = os.path.dirname(__file__)  # 当前文件所在路径
    upload_path = os.path.join(basepath, r'static\uploads',
      secure_filename(f.filename))  
    f.save(upload_path)
    return render_template('upload.html', msg = "上传文件成功!")
  return render_template('upload.html', msg = "选择上传文件")

## 直接下载文件的请求,用send_from_directory返回文件本体即可
@app.route('/static/uploads/<filename>')
def downfile(filename):
  basepath = os.path.dirname(__file__)
  upload_path = os.path.join(basepath, r'static\uploads')
  return send_from_directory(upload_path, filename = filename, as_attachment = True)

### 开始脚本  
if __name__ == '__main__':
  app.run(host = HOST, port = PORT, debug = True)